<?php
//Search

//** Each page that is "stand alone" must have this variable.

if(!isset($authorizedPage)) require('error.php');

sanitize($_GET['search']);

$search = "%".strtolower(trim($_GET['search'])) . "%";
$searchClean = strtolower(trim($_GET['search']));

$searchResults = Array();
if(strlen($search) == 2) die();

$query = "SELECT id, tags, title, steps, ingredients, materials, description FROM recipie WHERE LOWER(steps) LIKE '$search' OR LOWER(ingredients) LIKE '$search' OR LOWER(materials) LIKE '$search' OR LOWER(tags) LIKE '$search' OR LOWER(title) LIKE '$search' OR LOWER(description) LIKE '$search'";
$results = mysql_query($query) or die(mysql_error());


function matches($string, $search,$offset=0){
	$position = stripos($string, $search, $offset);
	if($position === FALSE) return 0;
	return 1 + matches($string, $search, $position + strlen($search));
}

function weightSort(Array $a, Array $b){
	if($a['weight'] == $b['weight']) return 0;
	return ($a['weight'] < $b['weight']); // ? -1 : 1;
}

$index = 0;
while($row = mysql_fetch_assoc($results)){
	$searchResults[$index]['recipieID'] = $row['id'];
	$searchResults[$index]['title'] = $row['title'];
	$searchResults[$index]['description'] = $row['description'];
	
	$weight = 0;
	$weight += matches($row['steps'], $searchClean);
	$weight += matches($row['ingredients'], $searchClean);
	$weight += matches($row['materials'], $searchClean);
	$weight += matches($row['description'], $searchClean);
	$weight += matches($row['title'], $searchClean);
	$weight += matches($row['tags'], $searchClean);
	
	$searchResults[$index]['weight'] = $weight;
	$index++;
}

//Display Results

if(count($searchResults) == 0){
	echo '<div class="noResult">';
	echo 'I am sorry to say but there are no results, so hey!';
	echo '</div>';
}
else
	usort($searchResults, "weightSort");
	
foreach($searchResults as $value){
	$description = $value['description'];
	$title = $value['title'];
	$rID = $value['recipieID'];
	$weight = $value['weight'];
	

	
	echo '<div class="result">';
	echo '<div class="rTitle"><a href="view.php?rid='.$rID.'">'.$title.'</a>';
	echo '<div class="rSmall">Found ' . $weight . ($weight > 1 ? " matches" : " match") . ".</div>"; 
	echo '</div>';
	echo '<div class="rDescription">' . $description . "</div>";
	echo '</div>';
	echo '<br />';
	
	
}

?>